﻿using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace msilgc.cbuilder.CSyntaxTree
{
    internal interface ICMethodCall : ICStatementWithAssignment
    {
        IDictionary<ParameterInfo, IVariable> Parameters { get; }
        MethodBase Method { get; }
        void Emit(StringBuilder builder, IMethodNameMapper methodNameMapper);
    }
    internal sealed class CMethodCall : ICMethodCall
    {
        public IDictionary<ParameterInfo, IVariable> Parameters { get; private set; }
        public MethodBase Method { get; private set; }
        public IVariable Target { get; set; }
        public bool OnStack { get; set; }

        public CMethodCall(MethodBase method, IDictionary<ParameterInfo, IVariable> parameters, IVariable returnVal) {
            Method = method;
            Parameters = parameters;
            Target = returnVal;
            OnStack = (Target != null);
        }
        
        public void Emit(StringBuilder builder) {
            Emit(builder, new NullMethodNameMapper());
        }

        public void Emit(StringBuilder builder, IMethodNameMapper methodNameMapper) {
            if(Target != null)
            {
                Target.Emit(builder);
                builder.Append(" = ");
            }
            builder.Append(methodNameMapper.MapMethodToName(Method));
            builder.Append("(");
            bool first = true;
            foreach (ParameterInfo parameter in Method.GetParameters())
            {
                if(first)
                {
                    first = false;
                }
                else
                {
                    builder.Append(",");
                }
                Parameters[parameter].Emit(builder);
            }
            builder.AppendLine(");");
        }
    }
}
